import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/common/ProfileDTO.dart';
import 'package:ichinesereader/models/common/Settings.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/dialogs/changeUserPasswordReactive.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerIndividual.dart';
import 'package:ichinesereader/widgets/sidebars/individualSidebar.dart';
import 'package:intl/intl.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:reactive_segmented_control/reactive_segmented_control.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as uHtml;

class IndividualProfileSettings extends StatefulWidget {
  static const String routeName = '/individual/profile';

  @override
  State<IndividualProfileSettings> createState() =>
      _IndividualProfileSettingsState();
}

class _IndividualProfileSettingsState extends State<IndividualProfileSettings> {
  final UserController _usercontroller = Get.find();
  final box = Hive.box('appconfig');
  int _currentLevel = 1;
  StudentDetailsEditFormModel formModel = StudentDetailsEditFormModel();

  @override
  void initState() {
    bool isIndividual = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Individual;
    if (isIndividual) {
      Future.delayed(Duration(milliseconds: 200), () {
        _usercontroller.getProfile();
      });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build individual ProfileSettings');

    int _selectedSidebarItem = RoutePages.individualPageItems
        .indexWhere((page) => page.route == Get.currentRoute);
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    final PageStyles _pageStyles = PageStyles();

    var form = formModel.form;
    var dateformat = new DateFormat('MM/dd/yyyy');
    List<DropdownMenuItem> _progressLevels = [];
    Constants.levelOptions.forEach((element) {
      _progressLevels.add(
        DropdownMenuItem(
          value: element.value,
          child: Text(
            element.label.toString(),
          ),
        ),
      );
    });
    return Scaffold(
      backgroundColor: Get.isDarkMode ? Colors.black : Colors.transparent,
      resizeToAvoidBottomInset: false,
      appBar: isSmallScreen
          ? AppBar(
              title: Text('Profile'.tr),
            )
          : null,
      drawer: isSmallScreen ? IndividualAppDrawer() : null,
      body: Container(
        decoration: _pageStyles.pageBoxDecoration(),
        child: Row(
          children: [
            Visibility(
                visible: !isSmallScreen,
                child: Container(
                    child: IndividualSidebarX(
                        selectedIndex: _selectedSidebarItem,
                        isBigScreen: isBigScreen))),
            Expanded(
              child: Container(
                //color: Colors.white,
                child: Obx(() {
                  if (_usercontroller.profile.value.userId != null) {
                    Settings _classSettings =
                        _usercontroller.profile.value.settings as Settings;
                    form.control('username').value =
                        _usercontroller.profile.value.userName;
                    form.control('security').value =
                        _usercontroller.profile.value.accessCode;
                    form.control('firstname').value =
                        _usercontroller.profile.value.firstName;
                    form.control('lastname').value =
                        _usercontroller.profile.value.lastName;
                    form.control('level').value =
                        _usercontroller.profile.value.level ?? 'level1';
                    form.control('email').value =
                        _usercontroller.profile.value.email;
                    if (_usercontroller.profile.value.dateOfBirth != null)
                      form.control('dateofbirth').value = dateformat.parse(
                          _usercontroller.profile.value.dateOfBirth.toString());
                    form.control('nickname').value =
                        _usercontroller.profile.value.nickName;
                    form.control('gender').value =
                        _usercontroller.profile.value.gender;
                    form.control('texttype').value =
                        _classSettings.language ?? 'Simplified';
                    form.control('audiotype').value =
                        _classSettings.lang ?? 'Mandarin';
                    form.control('pinyinenabled').value =
                        _classSettings.pinyin ?? true;
                    _usercontroller.setLanguage(_classSettings.language);
                    _usercontroller.setLang(_classSettings.lang);
                    _usercontroller.setPinyin(_classSettings.pinyin);

                    return Container(
                      margin: EdgeInsets.all(12.0),
                      decoration: BoxDecoration(
                        color: Get.isDarkMode
                            ? AppTheme.colors.darkTheme2
                            : Colors.white.withOpacity(0.9),
                        borderRadius: BorderRadius.circular(3.0),
                      ),
                      child: SingleChildScrollView(
                        primary: false,
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
                          child: ReactiveForm(
                            formGroup: form,
                            child: Column(
                              children: <Widget>[
                                ReactiveTextField(
                                  formControlName: 'username',
                                  style: Theme.of(context).textTheme.titleSmall,
                                  decoration: InputDecoration(
                                    labelText: 'User Name'.tr,
                                    labelStyle: TextStyle(
                                      color: Color(0xff666666),
                                      fontSize: 16.0,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  readOnly: true,
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                                ReactiveTextField(
                                  formControlName: 'security',
                                  style: Theme.of(context).textTheme.titleSmall,
                                  decoration: InputDecoration(
                                    labelText: 'Security Identifier'.tr,
                                  ),
                                  readOnly: true,
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                                ReactiveTextField(
                                  formControlName: 'email',
                                  style: Theme.of(context).textTheme.titleSmall,
                                  decoration: InputDecoration(
                                    labelText: 'Email'.tr,
                                  ),
                                  //readOnly: true,
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                                ReactiveTextField(
                                  formControlName: 'firstname',
                                  style: Theme.of(context).textTheme.titleSmall,
                                  decoration: InputDecoration(
                                    labelText: 'First Name'.tr,
                                  ),
                                  //readOnly: true,
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                                ReactiveTextField(
                                  formControlName: 'lastname',
                                  style: Theme.of(context).textTheme.titleSmall,
                                  decoration: InputDecoration(
                                    labelText: 'Last Name'.tr,
                                  ),
                                  //readOnly: true,
                                ),
                                SizedBox(
                                  height: 24,
                                ),
                                ReactiveSegmentedControl<String, String>(
                                  formControlName: 'gender',
                                  decoration: InputDecoration(
                                    labelText: 'Gender'.tr,
                                    border: OutlineInputBorder(),
                                    helperText: '',
                                  ),
                                  padding: const EdgeInsets.all(0),
                                  unselectedColor: Get.theme.primaryColorLight,
                                  children: {
                                    'male': Text('Male'.tr,
                                        style: TextStyle(
                                          color: Color(0xff00599b),
                                          fontSize: 16.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'female': Text('Female'.tr,
                                        style: TextStyle(
                                          color: Color(0xff00599b),
                                          fontSize: 16.0,
                                          letterSpacing: 1.0,
                                        )),
                                  },
                                ),

                                ReactiveTextField<DateTime>(
                                  formControlName: 'dateofbirth',
                                  //readOnly: true,
                                  decoration: InputDecoration(
                                    labelText: 'Birthday'.tr,
                                    suffixIcon: ReactiveDatePicker<DateTime>(
                                      formControlName: 'dateofbirth',
                                      firstDate: DateTime(1990),
                                      lastDate: DateTime(2030),
                                      builder: (context, picker, child) {
                                        return IconButton(
                                          onPressed: picker.showPicker,
                                          icon: const Icon(Icons.date_range),
                                        );
                                      },
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                                ReactiveTextField(
                                  formControlName: 'nickname',
                                  style: Theme.of(context).textTheme.titleSmall,
                                  decoration: InputDecoration(
                                    labelText: 'Nick Name'.tr,
                                  ),
                                  maxLength: 150,
                                ),
                                // SizedBox(
                                //   height: 12,
                                // ),
                                ReactiveDropdownField<dynamic>(
                                  formControlName: 'level',
                                  decoration: InputDecoration(
                                    labelText: 'Choose Level'.tr,
                                  ),
                                  items: _progressLevels,
                                  onChanged: (value) {
                                    int changedLevel = int.parse(value
                                        .toString()
                                        .replaceAll('level', ''));
                                    if (changedLevel < _currentLevel) {
                                      Get.defaultDialog(
                                        backgroundColor: Get.isDarkMode
                                            ? (Color(0xff333333))
                                            : Color.fromARGB(
                                                255, 234, 241, 238),
                                        title: 'WARNING'.tr,
                                        content: Container(
                                          width: 360,
                                          child: Text(
                                            "Level downgrade will result in DATA RESET for previous reading progress, all books and quizzes between the changing levels will require to redo as the result, however, the points earned will not be affected. Please confirm the changes, thanks.",
                                            style: TextStyle(
                                                fontWeight: FontWeight.bold,
                                                letterSpacing: 1,
                                                color: Get.isDarkMode
                                                    ? Color(0xffcccccc)
                                                    : Colors.black,
                                                fontSize: 20),
                                          ),
                                        ),
                                        onCancel: () {
                                          form.control('level').value =
                                              'level${_currentLevel.toString()}';
                                        },
                                        onConfirm: () {
                                          form.control('level').value = value;
                                          Navigator.of(context).pop();
                                        },
                                      );
                                    }
                                  },
                                ),
                                SizedBox(
                                  height: 24,
                                ),
                                ReactiveSegmentedControl<String, String>(
                                  formControlName: 'audiotype',
                                  decoration: InputDecoration(
                                    labelText: 'Audio'.tr,
                                    border: OutlineInputBorder(),
                                    helperText: '',
                                  ),
                                  padding: const EdgeInsets.all(0),
                                  unselectedColor: Get.theme.primaryColorLight,
                                  children: {
                                    'Mandarin': Text('Mandarin'.tr,
                                        style: TextStyle(
                                          color: Color(0xff00599b),
                                          fontSize: 16.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'Cantonese': Text('Cantonese'.tr,
                                        style: TextStyle(
                                          color: Color(0xff00599b),
                                          fontSize: 16.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'No_audio': Text('No Audio'.tr,
                                        style: TextStyle(
                                          color: Color(0xff00599b),
                                          fontSize: 16.0,
                                          letterSpacing: 1.0,
                                        )),
                                  },
                                ),
                                // SizedBox(
                                //   height: 12,
                                // ),
                                ReactiveSwitchListTile(
                                  title: Text(
                                    'Pinyin'.tr,
                                    style: Theme.of(context)
                                        .textTheme
                                        .displaySmall,
                                  ),
                                  subtitle: Text(
                                    'When text option set to NO TEXT, pinyin can not be displayed.'
                                        .tr,
                                    // style:
                                    //     Theme.of(context).textTheme.labelSmall,
                                  ),
                                  formControlName: 'pinyinenabled',
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                                ReactiveSegmentedControl<String, String>(
                                  formControlName: 'texttype',
                                  decoration: InputDecoration(
                                    labelText: 'Text'.tr,
                                    border: OutlineInputBorder(),
                                    helperText: '',
                                  ),
                                  unselectedColor: Get.theme.primaryColorLight,
                                  padding: const EdgeInsets.all(0.0),
                                  children: {
                                    'Simplified': Text('Simplified'.tr,
                                        style: TextStyle(
                                          color: Color(0xff00599b),
                                          fontSize: 16.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'Traditional': Text('Traditional'.tr,
                                        style: TextStyle(
                                          color: Color(0xff00599b),
                                          fontSize: 16.0,
                                          letterSpacing: 1.0,
                                        )),
                                    'No text': Text('No Text'.tr,
                                        style: TextStyle(
                                          color: Color(0xff00599b),
                                          fontSize: 16.0,
                                          letterSpacing: 1.0,
                                        )),
                                  },
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    ElevatedButton(
                                      child: Text('Subscribe'.tr),
                                      onPressed: () {
                                        if (GetPlatform.isWeb)
                                          launchInWebViewWithJavaScript(
                                              '${Constants.BaseURL}icr/student/individual/subscription');
                                        else
                                          Get.toNamed(
                                              '/individual/subscription');
                                      },
                                    ),
                                    SizedBox(
                                      width: 18,
                                    ),
                                    ElevatedButton(
                                      child: Text('Change Password'.tr),
                                      onPressed: () {
                                        showGeneralDialog(
                                            context: context,
                                            transitionDuration:
                                                Duration(milliseconds: 400),
                                            pageBuilder: (bc, ania, anis) {
                                              //return ChangeUserPasswordDialog();
                                              return ChangeUserPasswordReactiveDialog(
                                                  isTeacherOrSchooladmin:
                                                      false);
                                            });
                                      },
                                    ),
                                    SizedBox(
                                      width: 18,
                                    ),
                                    ReactiveFormConsumer(
                                      builder: (context, form, child) {
                                        ProfileDTO dto = new ProfileDTO();
                                        dto.email = form.control('email').value;
                                        if (form.control('dateofbirth').value !=
                                            null)
                                          dto.birthday = dateformat.format(form
                                              .control('dateofbirth')
                                              .value);
                                        dto.firstName =
                                            form.control('firstname').value;
                                        dto.lastName =
                                            form.control('lastname').value;
                                        dto.gender =
                                            form.control('gender').value;
                                        dto.nickName =
                                            form.control('nickname').value;
                                        dto.settings = new Settings();
                                        dto.settings?.pinyin =
                                            form.control('pinyinenabled').value;
                                        dto.settings?.lang =
                                            form.control('audiotype').value;
                                        dto.settings?.language =
                                            form.control('texttype').value;
                                        dto.level =
                                            form.control('level').value ??
                                                'level1';
                                        if (dto.settings?.language ==
                                            'No Text') {
                                          dto.settings?.pinyin = false;
                                        }
                                        return ElevatedButton(
                                            style: ButtonStyle(
                                                backgroundColor:
                                                    MaterialStateProperty.all(
                                                        Color(0xff1ab394))),
                                            child: Text(
                                              'Update'.tr,
                                              style: TextStyle(
                                                color: Color(0xffd8ffff),
                                                letterSpacing: 1.0,
                                              ),
                                            ),
                                            onPressed: () {
                                              if (form.valid) {
                                                _usercontroller.setLanguage(
                                                    dto.settings?.language);
                                                _usercontroller.setLang(
                                                    dto.settings?.lang);
                                                _usercontroller.setPinyin(
                                                    dto.settings?.pinyin);
                                                if (GetPlatform.isWeb) {
                                                  uHtml.window.localStorage[
                                                          'lang'] =
                                                      '${dto.settings?.lang ?? 'Mandarin'}';
                                                  uHtml.window.localStorage[
                                                          'language'] =
                                                      '${dto.settings?.language ?? 'Simplified'}';
                                                }

                                                _usercontroller
                                                    .updateProfile(dto)
                                                    .then((statusResult) {
                                                  if (statusResult.status ==
                                                      1000) {
                                                    showSnackMsg(
                                                        'Successfully updated');
                                                  } else {
                                                    showSnackMsg(
                                                        'Error to update');
                                                  }
                                                });
                                              }
                                            });
                                      },
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    );
                  } else {
                    return Text('');
                  }
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
